package com.scs.application.modules.fsd.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.scs.application.core.service.BaseServiceImpl;
import com.scs.application.core.utils.StringUtils;
import com.scs.application.modules.fsd.entity.FsdUserRole;
import com.scs.application.modules.fsd.mapper.UserRoleMapper;
import com.scs.application.modules.fsd.service.UserRoleService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 */
@Service
public class UserRoleServiceImpl extends BaseServiceImpl<UserRoleMapper, FsdUserRole> implements UserRoleService {
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean saveByUsers(String roleIds, String userId) {
        remove(new QueryWrapper<FsdUserRole>().eq("user_id",userId));
        Collection<FsdUserRole> userRole = new ArrayList<>();
        String[] roleIdArray = roleIds.split(",");
        for (String role_id:roleIdArray) {
            if (StringUtils.isBlank(role_id)) continue;
            FsdUserRole userrole = new FsdUserRole();
            userrole.setRoleId(role_id);
            userrole.setUserId(userId);
            userRole.add(userrole);
        }
        saveBatch(userRole);
        return true;
    }
    @Override
    public List<FsdUserRole> getByRoleId(String roleId) {
        return list(new QueryWrapper<FsdUserRole>().eq("role_id",roleId));
    }

    @Override
    public  List<Map<String, Object>>  getRolesByUserId(String userId){
        return baseMapper.getRolesByUserId(userId);
    }

    @Override
    public List<FsdUserRole> getUsersByRole(String id) {
            return baseMapper.getUsersByRole(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean changeUsersByRole(String userIds, String roleId) {
        remove(new QueryWrapper<FsdUserRole>().eq("role_id",roleId));
        Collection<FsdUserRole> userRole = new ArrayList<>();
        String[] userIdArray = userIds.split(",");
        for (String user_id:userIdArray) {
            if (StringUtils.isBlank(user_id)) continue;
            FsdUserRole userrole = new FsdUserRole();
            userrole.setRoleId(roleId);
            userrole.setUserId(user_id);
            userRole.add(userrole);
        }
        saveBatch(userRole);
        return true;
    }


}
